package com.zxx.pattern.interpretPattern.interpret;

import java.util.Stack;

/**
 * @author zxx on 2021/2/24
 */
public class Calculator {
    private String statement;
    private Node node;

    public void build(String statement) {
        Node left, right;
        Stack<Node> stack = new Stack<>();

        String[] stateArr = statement.split(" ");

        for (int i = 0; i < stateArr.length; i++) {
            if (stateArr[i].equalsIgnoreCase("*")) {
                left = (Node) stack.pop();

                int val = Integer.parseInt(stateArr[++i]);
                right = new ValueNode(val);
                stack.push(new MulNode(left, right));

            } else if (stateArr[i].equalsIgnoreCase("/")) {
                left = stack.pop();
                int val = Integer.parseInt(stateArr[++i]);
                right = new ValueNode(val);
                stack.push(new DivNode(left, right));

            } else if (stateArr[i].equalsIgnoreCase("%")) {
                left = stack.pop();
                int val = Integer.parseInt(stateArr[++i]);
                right = new ValueNode(val);
                stack.push(new ModNode(left, right));

            } else {
                stack.push(new ValueNode(Integer.parseInt(stateArr[i])));
            }
        }
        this.node = stack.pop();
    }

    public int compute() {
        return node.interpret();
    }
}
